/**
 *@Title: NIOChannelServer.java
 *@Description: TODO
 *@author:Lau
 *@date 2017年7月9日 下午4:45:00 
 *@version V1.0
 */
package com.lty.nio.channeltest;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/** 
* @ClassName: NIOChannelServer 
* @Description: 通道实例服务端
* @author Lau 
* @date 2017年7月9日 下午4:45:00 
*  
*/
public class NIOChannelServer {
	private ByteBuffer buff = ByteBuffer.allocate(1024);
	
	//创建一个int型buffer缓冲区视图，此视图的改变和buff是同步的，彼此可见
	private IntBuffer intBuff = buff.asIntBuffer();
	
	private SocketChannel clientChannel = null;
	private ServerSocketChannel serverChannel = null;
	
	/***
	 * 
	* @Title: openChannel 
	* @Description: 打开服务端的通道
	* @throws Exception
	* void
	* @throws
	 */
	public void openChannel() throws Exception{
		//建立一个新的连接通道
		serverChannel = ServerSocketChannel.open();
		
		//为新的连接通道设置端口
		serverChannel.socket().bind(new InetSocketAddress(8888));
		System.out.println("服务端通道已经打开...");
	}
	
	/***
	 * 
	* @Title: waitReqConn 
	* @Description: 等待客户端的请求连接
	* @throws Exception
	* void
	* @throws
	 */
	public void waitReqConn() throws Exception{
		while(true){
			clientChannel = serverChannel.accept();
			if(null != clientChannel){
				System.out.println("新的连接加入！");
			}
			
			processReq();//处理请求
			clientChannel.close();
		}
	}

	/** 
	* @Title: processReq 
	* @Description: 处理请求过来的数据
	* @param 
	* @return void
	* @throws 
	*/
	private void processReq()throws Exception {
		System.out.println("开始读取和处理客户端数据...");
		buff.clear();//把当前位置设置为0，上限值修改为容量的值
		clientChannel.read(buff);
		int result = intBuff.get(0) + intBuff.get(1);
		//buff.flip();
		buff.clear();
		
		intBuff.put(0, result);
		clientChannel.write(buff);
		System.out.println("读取和处理客户端数据完成！");
	}
	
	/***
	 * 
	* @Title: start 
	* @Description: 开启任务
	* @throws Exception
	* void
	* @throws
	 */
	public void start()throws Exception{
		//打开服务通道
		openChannel();
		
		//监听等待客户端请求
		waitReqConn();
		
		clientChannel.close();
		
		System.out.println("服务端处理完毕！");
		
	}
	
	public static void main(String[] args) throws Exception {
		new NIOChannelServer().start();
	}
	
}
